package com.pengpai.pangucms.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pengpai.pangucms.entity.SysFileinfo;
import com.pengpai.pangucms.service.ISysFileinfoService;
import com.pengpai.pangucms.utils.R;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wushuai
 * @since 2023-08-29
 */
@Controller
@RequestMapping("/sysFileinfo")
public class SysFileinfoController {

    @Resource
    private ISysFileinfoService sysFileinfoService;

    @PostMapping(value = "/upload")
    @ResponseBody
    public Object upload(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request) throws Exception {
        if(file.isEmpty()) return R.fail("文件上传失败！");
        String path = sysFileinfoService.upload(file, false);
        return R.success(path);
    }

//    @PostMapping(value = "/wangEditUpload")
    @RequestMapping(value = "/wangEditUpload", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object wangEditUpload(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        if(file.isEmpty()) {
            map.put("errno", 1);
            map.put("message", "WangEdit文件上传失败！");
            return map;
        }
        String uuidName = sysFileinfoService.upload(file, false);
        map.put("errno", 0);
        HashMap<String, Object> data = new HashMap<>();
        QueryWrapper<SysFileinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("file_code", uuidName);
        SysFileinfo fileinfo = sysFileinfoService.getOne(queryWrapper);
        if(uuidName != null && fileinfo != null){
            uuidName = "/files/" + uuidName + fileinfo.getFileSuff();
        }
        data.put("url", uuidName);
        data.put("alt", uuidName);
        data.put("href", uuidName);
        map.put("data", data);
        String jsonString = JSON.toJSONString(map);
        return jsonString;
    }

    @PostMapping(value = "/delete")
    @ResponseBody
    public Object delete(String uuid) throws Exception {
        if(uuid == null || "".equals(uuid)) return R.success("重置成功！");
        QueryWrapper<SysFileinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("file_code", uuid);
        sysFileinfoService.remove(queryWrapper);
        return R.success("重置成功！");
    }

}
